import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'course_data.dart';

class CourseTable extends StatelessWidget {
  final int index;

  const CourseTable({Key key, @required this.index})
      : assert(index != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: _buildEachWeek(
          context,
          index + 1, //注意index从0开始
          70.0,
          10,
          true,
          true,
        ),
      ),
    );
  }

  _buildColumnStyleB(
      {@required BuildContext context,
      @required int column,
      @required int currentWeek,
      @required double initHeight,
      @required int initSelectionNumber}) {
    Map<int, List<CourseData2>> courseData2 = {
      1: [
        CourseData2(
            id: "Android 1",
            name: "测试课程1",
            classroom: "201课室",
            week: [1],
            row: 1,
            rowSpan: 2,
            column: 1,
            teacher: "李老师",
            defaultColor: Color(0xff00ccff),
            customColor: null,
            top: 0),
        CourseData2(
            id: "Android 1",
            name: "测试22",
            classroom: "201课室",
            week: [1],
            row: 3,
            rowSpan: 3,
            column: 1,
            teacher: "李老师",
            defaultColor: Colors.greenAccent,
            customColor: null,
            top: 0),
      ],
      2: [
        CourseData2(
            id: "Android 1",
            name: "测试课程3",
            classroom: "201课室",
            week: [1],
            row: 3,
            rowSpan: 3,
            column: 2,
            teacher: "李老师",
            defaultColor: Colors.greenAccent,
            customColor: null,
            top: 0)
      ],
      3: [],
      4: [],
      5: [],
      6: [],
      7: []
    };
    var courseFlagMap = List.generate(initSelectionNumber, (index) => -1);
    var oneColumnCourse = <Container>[];
    var oneColumnData = courseData2[column].where((element) {
      return element.week.contains(currentWeek);
    }).toList();

    var sortedOneColumnData =
        _sortCourseData2(courseData: oneColumnData, currentWeek: currentWeek);

    for (int i = 0; i < sortedOneColumnData.length; ++i) {
      var element = sortedOneColumnData[i];
      for (int row = element.row; row < element.row + element.rowSpan; ++row) {
        if (row <= initSelectionNumber) {
          courseFlagMap[row - 1] = i;
        }
      }
    }
    for (int i = 0; i < courseFlagMap.length; ++i) {
      var flag = courseFlagMap[i];
      if (flag == -1) {
        oneColumnCourse.add(_buildFixedBox(initHeight));
      } else {
        var trueRowSpan = 1;
        while (i < courseFlagMap.length - 1) {
          if (flag == courseFlagMap[i + 1]) {
            ++trueRowSpan;
            ++i;
          } else {
            break;
          }
        }
        var one = sortedOneColumnData[flag];
        oneColumnCourse.add(Container(
            height: trueRowSpan * initHeight,
            child: _buildCourse2(
              course: one,
              currentWeek: currentWeek,
            )));
      }
    }
    return Column(
      children: oneColumnCourse,
    );
  }

//渲染每一周的课程信息
  _buildEachWeek(BuildContext context, int currentWeek, double initHeight,
      int initSelectionNumber, bool saturday, bool sunday) {
    return List.generate(8, (index) => index)
        .where((index) =>
            index >= 0 && index <= 5 ||
            saturday && index == 6 ||
            sunday && index == 7)
        .map<Widget>((column) {
      if (column == 0) {
        return _buildTableSidebar(
            initSelectionNumber: initSelectionNumber, initHeight: initHeight);
      } else {
        return _buildCourseColumn(context,
            column: column,
            currentWeek: currentWeek,
            initHeight: initHeight,
            initSelectionNumber: initSelectionNumber);
      }
    }).toList();
  }

//占位用的box
  _buildFixedBox(double initHeight) => Container(
        height: initHeight,
        child: SizedBox.expand(),
      );

  /// 返回每个子项中的颜色
  Color _buildCourseColor2(CourseData2 courseData, int currentWeek) {
    if (!courseData.week.contains(currentWeek)) {
      return Colors.grey[400];
    }
    if (courseData.customColor != null) {
      return courseData.customColor;
    } else {
      return courseData.defaultColor;
    }
  }

  _buildCourse2({@required CourseData2 course, @required int currentWeek}) =>
      SizedBox.expand(
        child: AnimatedContainer(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(50),
            color: _buildCourseColor2(course, currentWeek),
            boxShadow: [
              BoxShadow(
                  color: Colors.black26,
                  offset: Offset(2.0, 3.0), //阴影xy轴偏移量
                  blurRadius: 6.0, //阴影模糊程度
                  spreadRadius: 0.8 //阴影扩散程度
                  )
            ],
          ),
          duration: Duration(milliseconds: 500),
          curve: Curves.easeInOut,
          margin: EdgeInsets.all(20),
          padding: EdgeInsets.all(1.5),
        ),
      );

  _buildTableSidebar(
      {@required int initSelectionNumber, @required double initHeight}) {
    List<String> times = [
      "8:30 9:15",
      "9:20 10:05",
      "10:25 11:10",
      "11:15 12:00",
      "13:30 14:15",
      "14:20 15:05",
      "15:25 16:10",
      "16:15 17:00",
      "18:30 19:15",
      "19:20 20:05",
      "8:30 9:15",
      "9:20 10:05",
      "10:25 11:10",
      "11:15 12:00",
      "13:30 14:15",
      "14:20 15:05",
      "15:25 16:10",
      "16:15 17:00",
      "18:30 19:15",
      "19:20 20:05"
    ];
    return Expanded(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: List.generate(
              initSelectionNumber,
              (index) {
                final data = times[index].split(' ');
                final begin = data[0];
                final end = data[1];
                return Container(
                  height: initHeight,
                  child: SizedBox.expand(
                    child: Center(
                      child: Text.rich(
                        TextSpan(children: [
                          TextSpan(
                            text: '$begin\n',
                            style: TextStyle(fontSize: 13),
                          ),
                          TextSpan(
                            text: '${index + 1}\n',
                            style: TextStyle(
                              fontSize: 19,
                            ),
                          ),
                          TextSpan(
                            text: '$end',
                            style: TextStyle(fontSize: 13),
                          ),
                        ]),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                );
              },
            )));
  }

  _buildCourseColumn(BuildContext context,
      {@required int column,
      @required int currentWeek,
      @required double initHeight,
      @required int initSelectionNumber}) {
    return Expanded(
      flex: 2,
      child: _buildColumnStyleB(
          context: context,
          column: column,
          currentWeek: currentWeek,
          initHeight: initHeight,
          initSelectionNumber: initSelectionNumber),
    );
  }

  List<CourseData2> _sortCourseData2(
      {@required List<CourseData2> courseData, @required int currentWeek}) {
    //节数多的放前面
    return courseData
      ..sort((a, b) {
        if (a.rowSpan > b.rowSpan) {
          return -1;
        } else if (a.rowSpan == b.rowSpan) {
          return 0;
        } else {
          return 1;
        }
      })
      //不是本周的放前面
      ..sort((a, b) {
        if (a.week.contains(currentWeek) && !b.week.contains(currentWeek)) {
          return 1;
        } else if (!a.week.contains(currentWeek) &&
            b.week.contains(currentWeek)) {
          return -1;
        } else {
          return 0;
        }
      })
      //按课表层叠优先级排序
      ..sort((a, b) {
        return b.top - a.top;
      });
  }
}
